package tools

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

var (
	dbHost     = "127.0.0.1" // 数据库IP
	dbPort     = "3306"      // 数据库端口
	dbUser     = "root"      // 数据库用户名
	dbPassword = "1234"      // 数据库密码
	dbName     = "demo_db"   // 要使用的库名称
)

type AddressInfo struct {
	AddressId    uint32    `gorm:"primaryKey;column:address_id"`
	AddressName  string    `gorm:"column:address_name"`
	ParentId     uint32    `gorm:"column:parent_id"`
	AddressLevel uint8     `gorm:"column:address_level"` // 地址级别：1--省级；2--市级；3--县级；4--乡镇级；5--村级；
	CreateTime   time.Time `gorm:"column:create_time;autoUpdateTime:milli"`
	ModifyTime   time.Time `gorm:"column:modify_time;autoUpdateTime:milli"`
}

var (
	DB  *gorm.DB
	err error
)

// 数据表名称
func (AddressInfo) TableName() string {
	return "demo_table"
}

func init() {
	// 获取日志记录对象
	mLogger, mCtx := GetLogger()

	dsn := dbUser + ":" + dbPassword + "@tcp(" + dbHost + ":" + dbPort + ")/" + dbName + "?charset=utf8mb4&parseTime=True&loc=Local"
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: mLogger,
	})

	if err != nil {
		mLogger.Error(mCtx, "============================================")
		mLogger.Error(mCtx, "打开数据库连接失败！")
		mLogger.Error(mCtx, "============================================")
	}
}

// 判断记录是否存在
func IsExistRecord(addrInfo *AddressInfo) bool {
	var myAddressList []AddressInfo

	DB.Where("address_name=? and parent_id=? and address_level=?", addrInfo.AddressName, addrInfo.ParentId, addrInfo.AddressLevel).
		Find(&myAddressList)
	return len(myAddressList) > 0
}

// 添加记录
func AddRecord(addrInfo *AddressInfo) {
	DB.Create(addrInfo)
}

// 查询上级地址ID
func GetParentId(addrName string, addrLevel uint32) (parentId uint32) {
	var myAddress AddressInfo

	DB.Where("address_name=? and address_level=?", addrName, addrLevel).Find(&myAddress)

	parentId = myAddress.AddressId
	return
}
